<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2017/12/5
 * Time: 11:51
 */

namespace App\Helpers\Api;


use App\Exceptions\ApiException;
use EasyWeChat\Kernel\Exceptions\HttpException;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ExceptionReport
{
    use ApiResponse;

    /**
     * @var Exception
     */
    public $exception;
    /**
     * @var Request
     */
    public $request;

    /**
     * @var
     */
    protected $report;

    /**
     * ExceptionReport constructor.
     * @param Request $request
     * @param Exception $exception
     */
    function __construct(Request $request, Exception $exception)
    {
        $this->request = $request;
        $this->exception = $exception;
    }

    /**
     * @var array
     */
    public $doReport = [
        AuthenticationException::class => ['用户未授权', 401, 'no-login'],
        ModelNotFoundException::class => ['内容未审核或不存在', 404, 'error'],
        DecryptException::class => ['数据错误', 404, 'error'],
        //HttpException::class => ['公众号接口请求失败', 404, 'error'],
        NotFoundHttpException::class => ['地址错误', 404, 'error'],
        MethodNotAllowedHttpException::class => ['请求错误', 404, 'error'],
        ApiException::class => ['api-error', 400, 'error']
    ];

    /**
     * @return bool
     */
    public function shouldReturn()
    {
        if (!($this->request->wantsJson() || $this->request->ajax())) {
            return false;
        }

        foreach (array_keys($this->doReport) as $report) {

            if ($this->exception instanceof $report) {

                $this->report = $report;
                return true;
            }
        }

        return false;

    }

    /**
     * @param Exception $e
     * @return static
     */
    public static function make(Exception $e)
    {
        return new static(\request(), $e);
    }

    /**
     * @return mixed
     */
    public function report()
    {
        $message = $this->doReport[$this->report];
        if ($message[0] == 'api-error') {
            $message_str = $this->exception->getMessage();
        } else {
            $message_str = $message[0];
        }
        return $this->failed($message_str, $message[1], $message[2]);

    }

}